﻿using DevComponents.DotNetBar;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using PlanningGIS.ArcGIS;
using PlanningGIS.DataConvert.model;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Controls;
using PlanningGIS.Util.Log;
using PlanningGIS.Win.Controls;

namespace PlanningGIS.DataConvert.form
{
    public partial class FrmDataExcavate :Office2007Form
    {
        private IApplication m_Application = null;

        private IElement m_pElementUserDraw;
       
        //实现窗体的单态，每次弹出的窗口都为同一个
        private static FrmDataExcavate dataExcavateForm;
        private SelectXZQ selectXZQ1 = null;

        private IPolygon pPolygonCustom; //自定义导出范围图形
        private IPolygon pPolygonSurvey;//按测区范围

        private bool doing = false;//是否正在挖除中
        private bool breaked = false;//是否被用户终止

        private DataExcavate dataExcavate = null;

        public FrmDataExcavate(IApplication value)
        {
            InitializeComponent();
            m_Application = value;
        }

        /// <summary>
        /// 获取单态对象
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static FrmDataExcavate GetDataExcavateForm(IApplication value)
        {
            if (dataExcavateForm == null)
            {
                dataExcavateForm = new FrmDataExcavate(value);
            }

            return dataExcavateForm;
        }

        private void FrmDataExcavate_Load(object sender, EventArgs e)
        {
            //图幅选择控件赋控制器
            IHookHelper m_HookHelp = new HookHelperExClass();
            m_HookHelp.Hook = m_Application;
            chooseTuFu2.HookHelper = m_HookHelp;
            chooseFWX2.HookHelper = m_HookHelp;
            //自定义范围选择控件
            selectAreaControl2.afterButtonOkShift1 = new AfterButtonOkShift(AfterButtonOkEvent);
            selectAreaControl2.HookHelper = m_HookHelp;
            this.selectXZQ1 = new SelectXZQ();
            // 
            // tabControlPanel10
            // 
            this.tabControlPanel10.Controls.Add(this.selectXZQ1);
            this.tabControlPanel10.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControlPanel10.Location = new System.Drawing.Point(0, 26);
            this.tabControlPanel10.Name = "tabControlPanel10";
            this.tabControlPanel10.Padding = new System.Windows.Forms.Padding(1);
            this.tabControlPanel10.Size = new System.Drawing.Size(307, 457);
            this.tabControlPanel10.Style.BackColor1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(142)))), ((int)(((byte)(179)))), ((int)(((byte)(231)))));
            this.tabControlPanel10.Style.BackColor2.Color = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(237)))), ((int)(((byte)(254)))));
            this.tabControlPanel10.Style.Border = DevComponents.DotNetBar.eBorderType.SingleLine;
            this.tabControlPanel10.Style.BorderColor.Color = System.Drawing.Color.FromArgb(((int)(((byte)(59)))), ((int)(((byte)(97)))), ((int)(((byte)(156)))));
            this.tabControlPanel10.Style.BorderSide = ((DevComponents.DotNetBar.eBorderSide)(((DevComponents.DotNetBar.eBorderSide.Left | DevComponents.DotNetBar.eBorderSide.Right)
                        | DevComponents.DotNetBar.eBorderSide.Bottom)));
            this.tabControlPanel10.Style.GradientAngle = 90;
            this.tabControlPanel10.TabIndex = 3;
            // 
            // selectXZQ1
            // 
            this.selectXZQ1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.selectXZQ1.Location = new System.Drawing.Point(1, 1);
            this.selectXZQ1.Name = "selectXZQ1";
            this.selectXZQ1.Size = new System.Drawing.Size(305, 20);
            this.selectXZQ1.TabIndex = 0;

            selectXZQ1.HookHelper = m_HookHelp;
        }

        private void AfterButtonOkEvent(IGeometry pGeom, int shift)
        {
            if (pGeom == null || pGeom.IsEmpty || pGeom is IPoint)
            {
                return;
            }
            try
            {
                if (pGeom is IEnvelope)
                {
                    pGeom = ((IEnvelope)pGeom).ToPolygon();
                }
                else if (pGeom is ICircularArc)
                {
                    IPolygon pPolygon = new PolygonClass();
                    ISegmentCollection pSegCollection = pPolygon as ISegmentCollection;
                    object missing = System.Type.Missing;
                    pSegCollection.AddSegment(pGeom as ISegment, ref missing, ref missing);
                    pPolygon.SpatialReference = pGeom.SpatialReference;
                    pGeom = pPolygon;
                }

                if (pGeom == null || pGeom.IsEmpty) return;

                Cursor = Cursors.Default;

                pPolygonCustom = pGeom as IPolygon;
                GeometryUserDraw(pPolygonCustom);
            }
            catch (System.Exception)
            {

            }
            finally
            {

                this.WindowState = FormWindowState.Normal;

            }       
        }

        private void GeometryUserDraw(IPolygon pPolyUserDraw)
        {
            if (pPolyUserDraw == null || pPolyUserDraw.IsEmpty) return; ;
            IPolyline pPolyline = pPolyUserDraw.ToPolyline();

            IRgbColor pRgbColor = new RgbColorClass();
            pRgbColor.Red = 255;
            pRgbColor.Green = 155;
            pRgbColor.Blue = 0;

            IActiveView pActiveView = (m_Application.Document as IMxDocument).ActiveView;
            IGraphicsContainer pGeoContainer = pActiveView as IGraphicsContainer;
            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            ISimpleLineSymbol pLineSymbol = new SimpleLineSymbolClass();
            ILineElement pLineElement = new LineElementClass();
            pLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
            pLineSymbol.Color = pRgbColor;
            pLineSymbol.Width = 3;
            pLineElement.Symbol = pLineSymbol;
            m_pElementUserDraw = pLineElement as IElement;
            m_pElementUserDraw.Geometry = pPolyline;
            pGeoContainer.AddElement(m_pElementUserDraw, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pActiveView.Extent);
        }

        private void FrmDataExcavate_FormClosed(object sender, FormClosedEventArgs e)
        {
            (m_Application as IFramework).Tool = null;
            chooseTuFu2.ClearElements();
            //chooseXZQ1.ClearElements();

            IActiveView pAV = (m_Application.Document as IMxDocument).ActiveView;

            IGraphicsContainer pGeoContainer = pAV as IGraphicsContainer;

            if (m_pElementUserDraw != null)
                try
                {
                    pGeoContainer.DeleteElement(m_pElementUserDraw);
                    //IActiveView pAV = ((AxMapControl)statusController.Host).ActiveView;
                    pAV.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, pAV.Extent);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            dataExcavateForm = null;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void setSubPgbMax(int max)
        {
            progressBarSub.Maximum = max;
            progressBarSub.Minimum = 0;
            progressBarSub.Value = 0;
            Application.DoEvents();
        }

        private void setSubPgbCurrent(int current)
        {
            //progressBarSub.TextVisible = true;
            //progressBarSub.Text = "已处理" + current + "个";
            //Application.DoEvents();
            if (progressBarSub.Maximum == 0)
            {
                if (progressBarSub.ProgressType != DevComponents.DotNetBar.eProgressItemType.Marquee)
                    progressBarSub.ProgressType = DevComponents.DotNetBar.eProgressItemType.Marquee;
                progressBarSub.TextVisible = true;
                progressBarSub.Text = "已处理" + current + "个";
                progressBarSub.Update();
                Application.DoEvents();
            }
            else
            {
                if (progressBarSub.ProgressType != DevComponents.DotNetBar.eProgressItemType.Standard)
                    progressBarSub.ProgressType = DevComponents.DotNetBar.eProgressItemType.Standard;
                if (current <= progressBarSub.Maximum)
                {
                    progressBarSub.Value = (int)current;

                    double dRate = current * 100.0 / progressBarSub.Maximum;
                    int iRate = (int)Math.Floor(dRate);
                    progressBarSub.TextVisible = true;
                    progressBarSub.Text = "分进度：" + current.ToString() + "/" + progressBarSub.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                    //dataGridViewX1.UseWaitCursor = true;
                }
                else
                {
                    progressBarSub.Value = (int)progressBarSub.Maximum;
                    progressBarSub.TextVisible = false;
                    //dataGridViewX1.UseWaitCursor = false;
                }
                progressBarSub.Update();
                if (progressBarSub.Maximum < 200)
                    Application.DoEvents();
                else
                    if (current % (progressBarSub.Maximum / 100) == 0) Application.DoEvents();
            }
        }

        private void setAllPgbMax(int max)
        {
            progressBarAll.Maximum = max;
            progressBarAll.Minimum = 0;
            progressBarAll.Value = 0;
            Application.DoEvents();
        }

        private void setAllPgbCurrent(int current)
        {
            if (current <= progressBarAll.Maximum)
            {
                progressBarAll.Value = (int)current;

                double dRate = current * 100.0 / progressBarAll.Maximum;
                int iRate = (int)Math.Floor(dRate);
                progressBarAll.TextVisible = true;
                progressBarAll.Text = "总进度：" + current.ToString() + "/" + progressBarAll.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                //dataGridViewX1.UseWaitCursor = true;
            }
            else
            {
                progressBarAll.Value = (int)progressBarAll.Maximum;
                progressBarAll.TextVisible = false;
                //dataGridViewX1.UseWaitCursor = false;
            }
            progressBarAll.Update();
            if (progressBarAll.Maximum < 200)
                Application.DoEvents();
            else
                if (current % (progressBarAll.Maximum / 100) == 0) Application.DoEvents();
        }

        private void FrmDataExcavate_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!(m_Application as IFramework).IsMapCtrlactive)
            {
                MsgHelper.ShowInfomationMsgbox("请先切换到数据视图再进行此操作！");
                e.Cancel = true;
            }

            if (doing)
            {
                MsgHelper.ShowInfomationMsgbox("挖除还未结束，不能退出该窗口！");
                e.Cancel = true;
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (doing)
            {
                if (MsgHelper.ShowYesOrNoQueryMsgBox("是否要终止挖除操作？") == DialogResult.Yes)
                {

                    if (dataExcavate != null) dataExcavate.Stop();
                    breaked = true;
                }
            }
        }

        private void btnExcavate_Click(object sender, EventArgs e)
        {
            if (!(m_Application as IFramework).IsMapCtrlactive)
            {

                MsgHelper.ShowInfomationMsgbox("请先切换到数据视图再进行此操作！");
                return;
            }

            try
            {

                #region 判断需要挖除的数据是否为空，并列到List中
                List<IFeatureClass> pFeatClses = new List<IFeatureClass>();
                foreach (ListViewItem pListViewItem in this.lstvData.Items)
                {
                    if (pListViewItem.Tag != null && pListViewItem.Tag is IFeatureClass && pListViewItem.Checked)
                    {
                        pFeatClses.Add(pListViewItem.Tag as IFeatureClass);
                    }
                }

                if (pFeatClses.Count == 0)
                {
                    MsgHelper.ShowInfomationMsgbox("没有合适数据需要挖除！");
                    return;
                }
                #endregion

                switch (tabControl2.SelectedTab.Text)
                {
                    case "按图幅范围": //按图幅导出
                        if (chooseTuFu2.TuFus == null || chooseTuFu2.TuFus.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择图幅！");
                            return;
                        }
                        break;
                    case "按自定义范围": //按自定义范围
                        if (pPolygonCustom == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未划定范围！");
                            return;
                        }
                        break;

                    case "按测区范围":
                        pPolygonSurvey = chooseFWX2.PolygonFWX;
                        if (pPolygonSurvey == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择测区！");
                            return;
                        }
                        break;

                    case "按行政区范围":
                        pPolygonSurvey = selectXZQ1.GetGeometry() as IPolygon;
                        if (pPolygonSurvey == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("未选择行政区！");
                            return;
                        }
                        break;
                    default:
                        return;
                }

                dataExcavate = new DataExcavate();
                dataExcavate.SetProcessBarMax = setAllPgbMax;
                dataExcavate.SetProcessBarCurrent = setAllPgbCurrent;
                dataExcavate.SetSubProcessBarMax = setSubPgbMax;
                dataExcavate.SetSubProcessBarCurrent = setSubPgbCurrent;

                //if (chkCallBack.Checked)
                //{
                //    dataExcavate.CallbacknNum = Int32.Parse(txtCallback.ControlText);
                //}
                //else
                //{
                //    dataExcavate.CallbacknNum = 0;
                //}

                dataExcavate.FeatClses = pFeatClses;
                dataExcavate.Progress = chkProgress.Checked;

                switch (tabControl2.SelectedTab.Text)
                {
                    case "按图幅范围": //按图幅导出
                        var v = from o in chooseTuFu2.TuFus select o.Geometry;
                        dataExcavate.ExcavatePolygon = GeometryHelper.Union(v.ToList()) as IPolygon;
                        break;
                    case "按自定义范围": //按自定义范围
                        dataExcavate.ExcavatePolygon = pPolygonCustom;
                        break;

                    case "按测区范围":
                        dataExcavate.ExcavatePolygon = pPolygonSurvey;
                        break;

                    case "按行政区范围":
                        dataExcavate.ExcavatePolygon = pPolygonSurvey;
                        break;

                    default:
                        return;
                }

                doing = true;
                if (!dataExcavate.Operate())
                {
                    if (breaked)
                    {
                        LogHelper.WriteLog("挖除被终止。\n\n");
                        breaked = false;
                    }
                    else
                    {
                        LogHelper.WriteErrLog("挖除失败！！！\n\n");
                    }
                }
                else
                {
                    //MsgHelper.ShowInfomationMsgbox("挖除完毕！");
                }
            }
            catch(Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("挖除失败：" + ex.Message);
            }
            finally
            {
                doing = false;

                progressBarAll.Value = 0;
                progressBarSub.Value = 0;
                progressBarSub.Text = "";
                progressBarSub.ProgressType = DevComponents.DotNetBar.eProgressItemType.Standard;
                progressBarAll.Text = "";
            }


        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                IList<IFeatureClass> fclasslist = new List<IFeatureClass>();
                OpenDataDialog addData = new OpenDataDialog();

                addData.OnOkClick = delegate
                {
                    List<IDataNode> datanodes = addData.GetSelectNode<IDataNode>();
                    foreach (IDataNode datanode in datanodes)
                    {

                        if (datanode is FeatureClassNode)
                        {
                            fclasslist.Add(datanode.Open() as IFeatureClass);
                        }
                        else if (datanode is DatasetNode)
                        {
                            IEnumDataset datasetenum = datanode.Open().Subsets;
                            IDataset dataset = datasetenum.Next();
                            while (dataset != null)
                            {
                                fclasslist.Add(dataset as IFeatureClass);
                                dataset = datasetenum.Next();
                            }
                        }
                    }
                    foreach (IFeatureClass featureClass in fclasslist)
                    {
                        //IWorkspace pWorkspace1 = DataUpdateHelper.GetSDEWorkspace();
                        //IWorkspace pWorkspace2 = ((IDataset)featureClass).Workspace;
                        //if (CartoUtility.IsSameWorkspace(ref pWorkspace1, ref pWorkspace2) == false)
                        //{
                        //    MsgHelper.ShowWarningMsgbox("本系统中的更新功能仅支持规则文件中所配置的PlanningGIS版本的基础SDE数据！");
                        //    return;
                        //}

                        ListViewItem pListViewItem = new ListViewItem(((IDataset)featureClass).BrowseName);
                        pListViewItem.Tag = featureClass;
                        pListViewItem.Checked = true;
                        this.lstvData.Items.Add(pListViewItem);
                        //listView1.Tag = ((IDataset)featureClass).Workspace;
                    }
                    addData.Close();
                };
                addData.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("打开数据失败：" + ex.Message);
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lstvData.Items.Count == 0) return;
                if (this.lstvData.SelectedItems.Count == 0) return;

                foreach (ListViewItem pListViewItem in this.lstvData.SelectedItems)
                {
                    this.lstvData.Items.Remove(pListViewItem);
                }
                //if (this.listView1.Items.Count == 0) this.listView1.Tag = null;
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("移除失败：" + ex.Message);
            }
        }

        private void chkCallBack_Click(object sender, EventArgs e)
        {

        }
    }


}
